package com.qf.qfwemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.qfleadnewsmodel.user.pojos.ApUser;
import com.qf.qfleadnewsmodel.wemedia.dtos.LoginDto;
import com.qf.qfleadnewsmodel.wemedia.pojos.WmUser;
import com.qf.qfleadnewsutils.commons.AppJwtUtil;
import com.qf.qfwemedia.mapper.WmUserMapper;
import com.qf.qfwemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        String name = loginDto.getName();
        String password = loginDto.getPassword();

        if (StringUtils.isBlank(name) && StringUtils.isBlank(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            //利用phone和password进行匹配
            Wrapper<WmUser> qw = Wrappers.lambdaQuery(WmUser.class).eq(WmUser::getName,name);
            WmUser wmUser = baseMapper.selectOne(qw);
            if (wmUser == null){
                //手机号错误 -- 登录失败
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PHONE_ERROR);
            }else{
                //匹配密码 -- 基于加盐的方式，将明文进行md5运算，将得到的md5值和数据库存入的md5进行比对
                String salt = wmUser.getSalt();
                //将明文密码和盐值拼接后进行md5运算
                String md5 = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
                //将得到的md5和数据库的密码进行比对
                if (md5.equals(wmUser.getPassword())){
                    //密码正确，登录成功
                    //返回jwt串+同时要返回用户的信息
                    String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));

                    Map map = new HashMap();
                    map.put("token",token);

                    //频闭密码和盐值
                    wmUser.setPassword("");
                    wmUser.setSalt("");
                    map.put("user",wmUser);

                    return ResponseResult.okResult(map);
                }else{
                    //密码错误，登录失败
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }
        }
    }
}
